<?php


namespace app\common\job;

use app\common\library\Pay;
use think\Db;
use think\Exception;
use think\queue\Job;
use think\Cache;
use app\common\library\Mini;
use think\helper\Time;


class Subscribe
{
    public function sub(Job $job, $data)
    {
        $msg = "成功";
        Db::startTrans();
        try {
            $user_id = $data['user_id'];
            $num = Cache::get("sub_num.$user_id");
            $mini_openid = Db::name('user')->where(['id' => $user_id])->value('openid');
            if ($num < 5) {
                $res = Mini::sendMessage($data['encode'], $mini_openid, $data['newsdata'], "pages/index/index");
                error_log("\r\n" . var_export($res, true) . "\r\n", 3, __FILE__ . '----.log');
                if ($res['errcode'] === 0) {  //如果用户订阅了  成功收到订阅消息了 次数加1
                    if ($num == false) {
                        //离今天晚上12点还剩下多少秒
                        list($start, $end) = Time::today();
                        $time = $end - time();
                        Cache::set("sub_num.$user_id", 1, $time);
                    } else {
                        list($start, $end) = Time::today();
                        $time = $end - time();
                        Cache::set("sub_num.$user_id", $num + 1, $time);
                    }
                }
            } else {
                error_log("\r\n" . var_export($num, true) . "\r\n", 3, __FILE__ . '----.log');
            }
            $job->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $job->delete();
            echo $data['user_id'] . $data['content'] . "_(" . date("Y-m-d H:i:s", time()) . ")" . $e->getMessage();
            return true;
        }
        $job->delete();
        echo $data['user_id'] . $data['content'] . "-(" . date("Y-m-d H:i:s") . ")" . $msg;
        return true;
    }
}